<template>
  <div class="edit-container">
    <!-- <el-button size="small" @click="roleManage()" style="width: 200px; margin: 0 0 10px 8px"
      >编辑文件权限</el-button
    > -->
    <el-dialog
      width="60%"
      top="10px"
      title="文件权限管理"
      :visible.sync="roleDialog"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
    >
      <!-- 选择用户 -->
      <!-- {{ treeData }} -->
      <!-- <div class="title-item">当前用户文件权限</div>
      <div v-if="currentFileList.length === 0">暂无数据</div>
      <div v-if="currentFileList.length !== 0">
        <el-tag
          size="small"
          style="margin: 4px"
          :key="item.file_hash"
          v-for="item in currentFileList"
          >{{ item.name }}</el-tag
        >
      </div> -->

      <div class="title-item">选择目录</div>
      <!-- :default-checked-keys="[5]" -->
      <el-tree
        :data="treeData"
        ref="treeRef"
        node-key="id"
        show-checkbox
        default-expand-all
        :default-checked-keys="calcArr"
        @check-change="handleCheckChangeObj"
        :expand-on-click-node="false"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span style="margin-right: 20px">{{ node.label }}</span>
        </span>
      </el-tree>
      <div class="title-item">文件权限变更为</div>
      <!-- {{ selectData }} -->
      <!-- {{ clacData }} -->
      <div v-for="item in selectData" class="item" :key="item.name">
        <p class="item-title">目录：{{ item.name }}</p>
        <!-- <el-tag style="margin-right: 10px">目录：{{ item.name }}</el-tag> -->
        <el-button size="small" @click="selectAll(item)">全选</el-button>
        <el-button size="small" @click="selectReverse(item)">反选</el-button>
        <el-checkbox-group v-model="item.selected" v-if="item.opitons.length !== 0">
          <el-checkbox
            class="checkbox-item"
            v-for="item2 in item.opitons"
            :key="item2.id"
            :label="item2.id"
            :name="item2.id"
            >{{ item2.name }}</el-checkbox
          >
        </el-checkbox-group>
      </div>
      <div class="btn-line">
        <el-button @click="roleDialog = false">取消</el-button>
        <el-button @click="save" type="primary">保存</el-button>
      </div>
    </el-dialog>
  </div>

  <!-- 权限管理 -->
</template>

<script>
import { getData, postData, deleteData } from '@/service/getData';
import axios from 'axios';
export default {
  data() {
    return {
      roleDialog: true, // 权限管理
      data: [],
      selectData: [],
      clacData: [],
      userList: [],
      treeData: [],
      partition_namesList: [],
      currentFileList: [],
      calcArr: [],
      form: {
        username: [],
        assign_ids: [],
        remove_ids: [],
        folder_ids: [],
        file_ids: [],
      },
      uploadParams: {
        uploadUrl: '/agent/corrector/upload_original_file',
        data: {},
        headers: {
          Authorization: '',
        },
        name: 'file',
        fileLists: [],
      },
    };
  },
  props: {
    role: {
      type: Number,
      default: 111,
    },
  },
  mounted() {
    this.getTree();
    this.getUserList();
    let token = localStorage.getItem('token');
    this.uploadParams.headers['Authorization'] = 'Token ' + token;
    this.getFile();
  },
  methods: {
    calcCurrentFileList() {
      // 循环 currentFileList对象 ，如果currentFileList对象的id在selectData对象的selected数组中，就把currentFileList对象的name赋值给selectData对象的name
    },
    selectAll(obj) {
      // 全选
      obj.selected = obj.opitons.map((item) => item.id);
    },
    selectReverse(obj) {
      // 反选
      obj.selected = obj.opitons
        .filter((item) => !obj.selected.includes(item.id))
        .map((item) => item.id);
    },
    handleCheckChangeObj(type) {
      // x
      this.form.file_ids = [];
      let newArr = [];
      const tree = this.$refs.treeRef;
      if (tree) {
        let arr = [];
        let selectedNodes = []; // 获取所有选中的节点
        let nodes = [];
        tree.getCheckedNodes().forEach((item) => {
          arr.push(item.id); // 获取所有选中节点的id
          if (item.files.length > 0) {
            let optionNodes = [];
            let selected = [];
            item.files.forEach((item) => {
              nodes.push({
                name: item.name,
                id: item.id,
              });
              optionNodes.push({
                name: item.name,
                id: item.id.toString(),
              });

              // 获取所有选中节点的对象
              selectedNodes.push(item.id); // 获取所有选中节点的id
              // this.currentFileList 是否包含id 与 item.id相同的项 如果有的话 就把当前id push 到selected
              if (this.currentFileList.find((item2) => item2.id === item.id)) {
                selected.push(item.id.toString());
              }

              // selected.push(item.id.toString());
            });
            newArr.push({
              name: item.name,
              opitons: optionNodes,
              selected: selected,
            });
          }
        });
        this.form.folder_ids = arr; // 更新已选择的节点
        // this.form.assign_ids = selectedNodes; // 更新已选择的节点
        this.partition_namesList = nodes;
        this.selectData = newArr;
      }
    },

    getFile() {
      getData('api/knowledge_base/files/', {
        user_id: this.role,
      }).then((res) => {
        this.calcArr = [];
        this.currentFileList = [];

        const traverse = (arr) => {
          arr.forEach((item) => {
            item.label = item.name;
            this.calcArr.push(item.id); //已选中的文件夹列表

            this.currentFileList.push(...item.files);
            // if (item.files.length > 0) {
            //   let arr = [];
            //   item.files.forEach((item) => {
            //     arr.push(item.id.toString());
            //   });
            //   this.selectData.push({
            //     name: item.name,
            //     opitons: [],
            //     selected: arr,
            //   });
            // }

            if (item.children && item.children.length > 0) {
              traverse(item.children);
            }
          });
        };
        traverse(res);
      });
    },
    getUserList() {
      postData('rbac/user/get_user_list').then((res) => {
        console.log(res, 'res');
        res.user_list.forEach((item) => {
          if (item.username !== this.$store.state.user.username) {
            this.userList.push({
              key: item.id,
              label: item.username,
              disabled: false,
            });
          }
        });
      });
    },
    // 权限管理
    roleManage() {
      this.form = {
        username: [],
        assign_ids: [],
        remove_ids: [],
      };
      this.roleDialog = true;
    },
    getTree() {
      // 超级管理员 获取全部 文件树
      getData(`api/knowledge_base/files/?user_id=${this.$store.state.user.id}`).then((res) => {
        this.clacData = [];
        this.treeData = res;
        // 递归遍历数组，给每个对象添加label属性
        const traverse = (arr) => {
          arr.forEach((item) => {
            item.label = item.name;
            item.id = item.id.toString();
            item.files.forEach((file) => {
              this.clacData.push({
                key: file.id.toString(),
                label: file.name,
                disabled: false,
              });
            });
            if (item.children && item.children.length > 0) {
              traverse(item.children);
            }
          });
        };
        traverse(this.treeData);
        setTimeout(() => {
          this.handleCheckChangeObj();
        }, 1000);
      });
    },
    save() {
      this.form.assign_ids = [];
      this.selectData.forEach((item) => {
        item.selected.forEach((id) => {
          this.form.assign_ids.push(id);
        });
      });

      this.form.remove_ids = []; // 清空已选择的节点

      this.clacData.forEach((item) => {
        if (!this.form.assign_ids.includes(item.key)) {
          this.form.remove_ids.push(item.key.toString());
        }
      });
      // 处理节点点击事件的逻辑
      // 将formData 对象
      axios
        .post(
          'api/knowledge_base/files/files_set_perm/',
          {
            user_ids: [this.role],
            assign_ids: this.form.assign_ids,
            remove_ids: this.form.remove_ids,
          },
          {
            headers: {
              Authorization: this.uploadParams.headers['Authorization'],
            },
          },
        )
        .then((res) => {
          this.roleDialog = false;
          // this.getTree();
          this.$message({
            type: 'success',
            message: '保存成功',
          });
          //
        })
        .catch((err) => {});
    },
  },
};
</script>

<style scoped lang="scss">
.title-item {
  margin: 10px 0;
  background: #e1f2f7;
  padding: 4px 10px;
}
.btn-line {
  padding: 10px;
  text-align: right;
}
.checkbox-item {
  padding: 10px 0;
}
.edit-container {
  text-align: left;
}
.item {
  background: #f7f7f7;
  margin: 10px 0;
  padding: 10px;
}
.item-title {
  color: #21b5e2;
  padding-bottom: 10px;
  border-bottom: 1px solid #21b5e2;
}
</style>
